import * as THREE from 'three'

/**
 * 创建流体墙体材质
 * option =>
 * params bgUrl flowUrl
 * **/
const createWallMaterial = ({
  bgTexture,
  flowTexture
}: {
  bgTexture: THREE.Texture
  flowTexture: THREE.Texture
}) => {
  // 顶点着色器
  const vertexShader = `
    varying vec2 vUv;
    varying vec3 fNormal;
    varying vec3 vPosition;
    void main(){
      vUv = uv;
      vPosition = position;
      vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
      gl_Position = projectionMatrix * mvPosition;
    }
  `;
  // 片元着色器
  const fragmentShader = `
    uniform float time;
    varying vec2 vUv;
    uniform sampler2D flowTexture;
    uniform sampler2D bgTexture;
    void main( void ) {
      vec2 position = vUv;
      vec4 colora = texture2D( flowTexture, vec2( vUv.x, fract(vUv.y - time )));
      vec4 colorb = texture2D( bgTexture , position.xy);
      gl_FragColor = colorb + colorb * colora;
    }
  `;
  // 允许平铺
  flowTexture.wrapS = THREE.RepeatWrapping;
  return new THREE.ShaderMaterial({
    uniforms: {
      time: {
        value: 0,
      },
      flowTexture: {
        value: flowTexture,
      },
      bgTexture: {
        value: bgTexture,
      },
    },
    transparent: true,
    // 自身能否遮挡
    depthWrite: false,
    // 深度测试，其它物体是否能遮挡此材质
    depthTest: true,
    side: THREE.DoubleSide,
    vertexShader: vertexShader,
    fragmentShader: fragmentShader,
  });
};

export default createWallMaterial